/**
 * @file PacketListener.h
 * @brief 
 * 		包监听器---从raw socket中获取网络层包，存入队列供resolver处理
 * @author Zyan (zyishere2001@qq.com)
 * @version 1.0
 * @date 2022-05-07
 * 
 * @copyright Copyright (c) 2022  Zyanishere2001
 * 
 * @par 修改日志:
 * V1.0_0507 基础功能--监听缓存
 */
#ifndef _PACKET_LISTENER
#define _PACKET_LISTENER

#include "EventLoopThread.h"
#include "hv.h"
#include "SafeQueue.h"
#include "Logger.h"

using namespace hv;

struct Packet_t {
	int len;
	unsigned char* data;
};

class PacketListener{
public:
	//socket
	SOCKET listener;
	SOCKET setupRawSocket();
public:
	PacketListener(const char* ip, SafeQueue<Packet_t>& queue);
	~PacketListener();

private:
	//要监听的ip
	const char* ip;
	
	//工作线程
	EventLoopThread listeningThread;
	const EventLoopPtr& loop = listeningThread.loop();
	
	//缓冲
	unsigned char buffer[8 * 1024] = { 0 };
	SafeQueue<Packet_t>& packetQueue;
	inline void produce(Packet_t packet) {
		this->packetQueue.Produce(std::move(packet));
	}
	Packet_t copy(unsigned char* src, int len) {	
		auto copy = (unsigned char*)hv_zalloc(sizeof(unsigned char) * len);
		memcpy(copy, buffer, len);
		Packet_t packet = { len, copy };
		return packet;
	}

protected:
	void startListening();
	void stopListening();

};

#endif

